package com.yiman.project.system.service.impl;

import com.yiman.framework.web.domain.Ltree;
import com.yiman.project.system.mapper.MenuMapper;
import com.yiman.project.system.model.Menu;
import com.yiman.project.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: Mr.yang
 * @create: 2019-06-05
 **/
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;


    @Override
    public List<Menu> selectMenusByUserId(String userId) {
        List<Menu> list = menuMapper.selectMenuNormalAll();
        List<Menu> removeList = new ArrayList<>();
        for (Menu m1 : list){
            for(Menu m2 : list){
                if(m1.getMenuId().equals(m2.getParentId())){
                    if (m1.getChildren()==null){
                        m1.setChildren(new ArrayList<Menu>());
                    }
                    m1.getChildren().add(m2);
                    removeList.add(m2);
                }
            }
        }
        list.removeAll(removeList);
        return list;
    }

    @Override
    public List<Ltree> getLtreeMenus(Integer roleId) {
        List<Menu> list = menuMapper.selectMenuNormalAll();
        List<Integer> menuList = null;
        if(roleId != null){
            menuList = menuMapper.selectMenuTree(roleId);
        }
        List<Ltree> treeList = new ArrayList<>();
        for (Menu m : list){
            Ltree tree = new Ltree();
            tree.setId(m.getMenuId());
            tree.setpId(m.getParentId());
            tree.setTitle(m.getMenuName());
            if(menuList != null){
                tree.setChecked(menuList.contains(m.getMenuId()));
            }
            treeList.add(tree);
        }
        getLtreeList(treeList);
        return treeList;
    }

    public List<Ltree> getLtreeList(List<Ltree> treeList){
        List<Ltree> removeList = new ArrayList<>();

        for (Ltree t1: treeList) {
            for (Ltree t2: treeList) {
                if(t1.getId().equals(t2.getpId())){
                    if(t1.getChildren() == null){
                        t1.setChildren(new ArrayList<>());
                    }
                    t1.getChildren().add(t2);
                    t1.setChecked(false);
                    removeList.add(t2);
                }
            }
        }
        treeList.removeAll(removeList);


        return treeList;
    }
}
